package com.xuelang.pipeline.app.pipeline.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xuelang.hiforce.base.tracing.TracingUtils;
import com.xuelang.hiforce.base.utils.message.Message;
import com.xuelang.pipeline.app.pipeline.GroupService;
import com.xuelang.pipeline.app.pipeline.converter.GroupDTOToGroupConverter;
import com.xuelang.pipeline.client.common.constant.Constant;
import com.xuelang.pipeline.client.common.exception.BizException;
import com.xuelang.pipeline.client.common.request.PageParam;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.common.util.BizAssert;
import com.xuelang.pipeline.client.pipeline.dto.GroupDTO;
import com.xuelang.pipeline.client.pipeline.dto.GroupQuery;
import com.xuelang.pipeline.client.pipeline.dto.PipelineGroupQuery;
import com.xuelang.pipeline.domain.pipeline.Group;
import com.xuelang.pipeline.domain.pipeline.PipelineGroup;
import com.xuelang.pipeline.domain.pipeline.service.GroupDomainService;
import com.xuelang.pipeline.domain.pipeline.service.PipelineGroupDomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 流水线分组服务实现类
 *
 * @author xiwen.zxg
 * @since 2024/5/15
 */
@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    GroupDomainService groupDomainService;

    @Autowired
    PipelineGroupDomainService pipelineGroupDomainService;

    @Override
    public PageRecord<GroupDTO> pageList(PageParam<GroupQuery> dtoPageParam) {
        GroupQuery condition = dtoPageParam.getCondition();
        condition = condition == null ? new GroupQuery() : condition;
        PageRecord<Group> pageRecord = groupDomainService.pageList(
                dtoPageParam.getCurrentPage(),
                dtoPageParam.getPageSize(),
                condition);
        return new PageRecord<>(
                pageRecord.getCurrentPage(),
                pageRecord.getPageSize(),
                pageRecord.getTotalCount(),
                pageRecord.getTotalPages(),
                pageRecord.getRecords().stream().map(GroupDTOToGroupConverter.INSTANCE::groupToGroupDTO).collect(Collectors.toList()));
    }

    @Override
    public List<GroupDTO> list(GroupQuery groupQuery) {
        return groupDomainService.list(groupQuery).stream().map(GroupDTOToGroupConverter.INSTANCE::groupToGroupDTO).collect(Collectors.toList());
    }


    @Override
    public Boolean add(GroupDTO groupDTO) {
        String name = groupDTO.getName();
        BizAssert.notNull(name, "name不能为空");

        Group group = GroupDTOToGroupConverter.INSTANCE.groupDTOToGroup(groupDTO);
        // 检查非默认分组名称是否与内置分组相同，若相同则报错
        if ((Objects.isNull(group.getIsDefault()) || group.getIsDefault() == 0)&&
                (group.getName().equals(Constant.DEFAULT_MY_FAVORITE) || group.getName().equals(Constant.DEFAULT_MY_PART))) {
            throw new BizException(Message.code("GROUP-NAME-CANNOT-BE", group.getName()).getDisplayText());
        }

        group.setUuid(IdUtil.fastSimpleUUID());
        return groupDomainService.save(group);
    }

    @Override
    public Boolean batchSaveOrUpdate(List<GroupDTO> groupDTOList) {
        BizAssert.notEmpty(groupDTOList, "批量添加分组的数组不能为空");
        List<Group> groupList = groupDTOList.stream()
                .map(GroupDTOToGroupConverter.INSTANCE::groupDTOToGroup).collect(Collectors.toList());
        for(Group group : groupList){
            // 检查非默认分组名称是否与内置分组相同，若相同则报错
            if ((Objects.isNull(group.getIsDefault()) || group.getIsDefault() == 0)&&
                    (group.getName().equals(Constant.DEFAULT_MY_FAVORITE) || group.getName().equals(Constant.DEFAULT_MY_PART))) {
                throw new BizException(Message.code("GROUP-NAME-CANNOT-BE", group.getName()).getDisplayText());
            }
        }

        return groupDomainService.batchSaveOrUpdate(groupList, TracingUtils.getUserId(), new Date());
    }

    @Override
    public Boolean update(GroupDTO groupDTO) {
        BizAssert.notNull(groupDTO.getUuid(), "uuid不能为空");
        BizAssert.notNull(groupDTO.getName(), "name不能为空");
        Group group = GroupDTOToGroupConverter.INSTANCE.groupDTOToGroup(groupDTO);
        // 检查非默认分组名称是否与内置分组相同，若相同则报错
        if ((Objects.isNull(group.getIsDefault()) || group.getIsDefault() == 0)&&
                (group.getName().equals(Constant.DEFAULT_MY_FAVORITE) || group.getName().equals(Constant.DEFAULT_MY_PART))) {
            throw new BizException(Message.code("GROUP-NAME-CANNOT-BE", group.getName()).getDisplayText());
        }
        return groupDomainService.update(group);
    }

    @Override
    public Boolean delete(String uuid) {
        BizAssert.notNull(uuid, "uuid不能为空");
        return groupDomainService.delete(uuid);
    }

    @Override
    public GroupDTO query(String uuid) {
        BizAssert.notNull(uuid, "uuid不能为空");
        return GroupDTOToGroupConverter.INSTANCE.groupToGroupDTO(groupDomainService.query(uuid));
    }

    @Override
    public Boolean modifyPipelineGroups(PipelineGroupQuery query) {
        return pipelineGroupDomainService.modifyPipelineGroups(query, TracingUtils.getUserId());
    }

    @Override
    public Boolean addFavoritePipeline(String pipelineCode) {
        // 找到当前用户的收藏夹分组
        GroupQuery groupQuery = new GroupQuery();
        groupQuery.setName(Constant.DEFAULT_MY_FAVORITE);
        groupQuery.setIsDefault(1);
        List<Group> targetGroupResult = groupDomainService.list(groupQuery);
        if (CollectionUtils.isEmpty(targetGroupResult)) {
            throw new BizException(Message.code("USER-FAVORITE-GROUP-NOT-EXIST", TracingUtils.getUserName()).getDisplayText());
        }

        // 添加进收藏夹
        Group myFavorite = targetGroupResult.get(0);
        return pipelineGroupDomainService.save(PipelineGroup.builder()
                .pipelineCode(pipelineCode)
                .groupUuid(myFavorite.getUuid())
                .build());
    }

    @Override
    public Boolean removeFavoritePipeline(String pipelineCode) {
        // 找到当前用户的收藏夹分组
        GroupQuery groupQuery = new GroupQuery();
        groupQuery.setName(Constant.DEFAULT_MY_FAVORITE);
        List<Group> targetGroupResult = groupDomainService.list(groupQuery);
        if (CollectionUtils.isEmpty(targetGroupResult)) {
            throw new BizException(Message.code("USER-FAVORITE-GROUP-NOT-EXIST", TracingUtils.getUserName()).getDisplayText());
        }

        // 流水线移出收藏夹
        Group myFavorite = targetGroupResult.get(0);
        return pipelineGroupDomainService.deleteByCondition(PipelineGroup.builder()
                .groupUuid(myFavorite.getUuid())
                .pipelineCode(pipelineCode)
                .build());
    }

}
